/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    InspectRecordLayout, InternalItemProps, OriginalViewProps, useItemInputControl,
} from "../../common/base";
import {assertNamesUnique, createItem, EditorAreaConfig,} from "../../common/eHelper";
import {useRecordListSubX} from "../../hook/useRecordListSub";
import {EditStorageContext} from "../../StorageContext";
import {
    BlobInputList, Button, CheckSwitch, InputLine, LineColumn, Text, TextArea, useToast
} from "customize-easy-ui-component";
import {useMedia} from "use-media";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";

export const OriginalView=
    React.forwardRef((
        { action: modAction,  verId, repId='', inp, rep}:OriginalViewProps, ref
    ) => {
      const {storage, setStorage} =React.useContext(EditStorageContext) as any;
      const { _STRENGTH_VFB: SubRepIds }=storage;
      if(undefined===SubRepIds)
         return <div>请先确定网络和服务器是正常的。然后才考虑是否要做：
                      <Button intent='danger' onPress={() => setStorage({...storage, _STRENGTH_VFB: [] }) }>
                      还没有数据！立刻初始化</Button></div>;
      //再一次确认，不能去掉：：避免hook报错, 分项报告模板的：【有可能】出现错，否则也没必要拆分两个组件做嵌套
      return <OriginalViewInner ref={ref} action={modAction} verId={verId} repId={repId} rep={rep}/>
} );

/**为了解决useProjectListAs({count: refCount } )因为变动{前面storage数据{有STRENGTH_VFB没有THICK_MS}和后面storage{有THICK_MS}数据不一样的}，导致hook报错！
 * 只好拆分成2层次嵌套拼装的俩组件了。父组件可以逻辑return子组件可用hook，不违反hook规则不报错。
 * */
const OriginalViewInner=
    React.forwardRef((
        { action: modAction,  verId, repId='', rep}:OriginalViewProps, ref
    ) => {
        const titleRender = (store: any) => {
            const firstTag=store?.部件;
            return <> { `[${firstTag}] `} </>;
        }
      const {list}=useRecordListSubX(ref,rep,repId,recordPrintList,modAction,verId,'STRENGTH_VFB',titleRender);
      return <React.Fragment>
        {list}
      </React.Fragment>;
} );



const itemA概要=['部件','检测结果'];
export const item校核依据=[['依受压','依据GB/T 16507-2013《水管锅炉 第4部分 受压元件强度计算》'],['依08','依据GB/T 9222-2008《水管锅炉受压元件强度计算》'],
            ['依88','依据GB/T 9222-1988《水管锅炉受压元件强度计算》'],['依火力','依据DL/T 5054《火力发电厂汽水管道设计技术规定》']];
item校核依据.forEach(([name, title], i: number) => {
        itemA概要.push(name as string);
});
export const PartSummary=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd,label}:InternalItemProps,  ref
    ) => {
        const [getInpFilter] = useMeasureInpFilter(null, itemA概要, );
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show} redId={redId}
                                 nestMd={nestMd} alone={alone} label={label!}>
                <Text variant="h5">{label}：</Text>
                <InputLine label='部件名称：'>
                    <BlobInputList value={inp?.部件 || ''} rows={1}
                                   onListChange={v => setInp({...inp, 部件: v || undefined})}/>
                </InputLine>
                校核依据{'>>'}
                <LineColumn>
                    {item校核依据.map(([name, desc]: any, i: number) => {
                        return <InputLine key={i} label={`${desc}:`}>
                            <CheckSwitch checked={inp?.[name] || false}
                                         onChange={e => setInp({...inp, [name]: inp?.[name] ? undefined : true})}/>
                        </InputLine>;
                    })}
                </LineColumn>
                校核结论：
                <BlobInputList value={inp?.检测结果 || ''} rows={3}
                               onListChange={v => setInp({...inp, 检测结果: v || undefined})}/>
            </InspectRecordLayout>
        );
    });

//【特殊布局】放大编辑框：
const editCalcCB=(obj: any, setObj: (arg: any) => void)=>{
    return <div id={'largeCalcT'}  className={'LargeCalc'}
                css={{           // "div:has(&) InputLine__Head": {minHeight:'22rem'},
                    "div:has(&).InputLine__Head":{display: 'block',},
                }}>
        <TextArea value={obj?.C ||''} rows={4}
                  onChange={e => setObj({ ...obj, C: e.currentTarget.value})}/>
    </div>
};
export const config测量 = [['名称', 'n', 130], ['符号', 'f', 40], ['单位', 'u', 50],
                ['计算及数据来源', 'C', 230, editCalcCB], ['结果', 'r', 120]] as Each_ZdSetting[];
const itemA测量 = ['测量表',];
export const EvaluationForm =
    React.forwardRef(({children, show, alone = true, refWidth, redId, nestMd,label}: InternalItemProps, ref
    ) => {
        const [getInpFilter] = useMeasureInpFilter(null, itemA测量, );
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const [render]=useTableEditor({
                        headview: undefined, inp, setInp, config: config测量, table: '测量表',  maxRf:3 });

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                <Text variant="h5">{label}：</Text>
                {render}
            </InspectRecordLayout>
        );
    } );


/**【特殊点】对于可重复分项框架模式的：表格调整setStorage({ _tblFixed: 必须点击“全部项目一起确认”才能立刻更新表格各列的宽度，需要多个按钮的点击，主报告的不需要;
 * 【分项表格】 【分项助手】 可重复分项  JSON.parse(parentOrc?._tblFixed??'[]')   【分项工具】 非主报告底下的。
 * */
const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const doCheckNames = React.useCallback((verId: string) => {
            const result = assertNamesUnique([{value: rep?.tzFields},
                // {value: config测量仪, type:'esnt'},
                {value:[...itemA概要, ...itemA测量, ]},
            ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const {storage, setStorage} =React.useContext(EditStorageContext) as any;
        const getInpFilter = React.useCallback((par: any) => {
            const {_tblFixed, } =par||{};
            return {_tblFixed, };
        }, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {process.env.REACT_APP_TEST==='true' && <><div>
                    <Text variant="h5">构建开发模板时的工具：校验模板的存储name冲突；</Text>
                    <Button intent='primary' onPress={() => doCheckNames(verId!)}>校验模板name唯一性</Button>
                    <Text variant="h5">设置待测试表格的各列宽度：</Text>
                    <TextArea value={storage?._tblFixed || ''} rows={2} onChange={e =>{
                        JSON.parse(e.currentTarget.value??'[]');
                        setStorage({ ...storage, _tblFixed: e.currentTarget.value || undefined}); }}/>
                </div></>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });

const recordPrintList = [
    createItem('Entrance', <EntranceSetup/>),
    createItem('PartSummary', <PartSummary label={'强度校核报告'}/>),
    createItem('EvaluationForm', <EvaluationForm label={'强度校核报告-计算及数据来源'}/>),
] as EditorAreaConfig[];
